package com.qk.manangement.task;

import com.qk.common.utils.AliOssUtil;
import com.qk.manangement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CleanOssTask {

    @Autowired
    private UserService userService;
    @Autowired
    private AliOssUtil oss;

    //7天执行一次
    @Scheduled(cron = "0 0 0/7 * * ?")
    public void cleanOss(){

        List<String> dbUserImageList = userService.listByUpdateTime().stream().map( user -> {
                    String image = user.getImage();
                    if (image != null) {
                        int index = image.indexOf("avatar/");
                        if (index != -1) {
                            return image.substring(index);
                        }
                    }
              return null;  }
                ).filter(image -> image != null).collect(Collectors.toList());


        oss.list().stream().filter(image -> !dbUserImageList.contains(image)).forEach(oss::delete);

    }
}
